<template>
  <el-dialog ref="dialog" :visible.sync="dialogModel" :title="$t('business.customSearch')" @close="handleClose" :close-on-press-escape="true" custom-class="customer-search-dialog" size="small">
    <el-form size="mini" class="formbody" ref="customizeForm" :form="formData" label-position="left" label-width="60px">
      <el-form-item :label="$t('public.menu')" key="kMenus">
        <el-select v-model="formData.menu">
          <el-option v-for="(item,index) in menus" :key="index" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('customer.CustomerSearch.name')" key="name">
        <el-input v-model="formData.name" size="mini" class="width188"></el-input>
      </el-form-item>
      <el-form-item :label="$t('customer.CustomerSearch.conditional')" key="type">
         <el-radio-group v-model='formData.type'>
          <el-radio label="and">{{$t('customer.CustomerSearch.allMeet')}}</el-radio>
          <el-radio label="or">{{$t('customer.CustomerSearch.anyContent')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('customer.CustomerSearch.condition')" v-for="(item, index) in conditionData" :key="index">
          <el-select v-model="chooseObject[index.toString()]"
                    :placeholder="$t('public.pleasePick')" filterable>
            <el-option v-for="(option,idx) in searchOptions" :key="idx" @click.native="labelChange(item,index)" :label="option.label" :value="option.name">
            </el-option>
          </el-select>
          <span class="padding font12">{{searchOptions[item].inputType === 'time' ? $t('public.between'): $t('public.equal')}}</span>
          <el-select class="width196" v-if="searchOptions[item].inputType === 'select'" filterable v-model="condition[index][item]"
                    :placeholder="$t('public.pleasePick')">
            <el-option v-for="(option,index) in searchOptions[item].data" :key="index" :label="option.label" :value="option.value">
            </el-option>
          </el-select>
          <el-input v-model="condition[index][item]" size="mini" v-if="searchOptions[item].inputType === 'input'" class="width169"></el-input>
          <div style="display:inline-block" v-if="searchOptions[item].inputType === 'selectAndInput'">
            <el-select class="width169" filterable v-model="condition[index]['stepFlow']"
            :placeholder="$t('public.pleasePick')" @change="(val) => handleChange(val, index)">
              <el-option v-for="(option,index) in searchOptions[item].data" :key="index" :label="option.label" :value="option.value">
              </el-option>
            </el-select>
            <el-select class="width169" style="margin-left:5px" filterable v-model="condition[index][item]"
            :placeholder="$t('public.pleasePick')">
              <el-option v-for="(option,index) in stepData[index]" :key="index" :label="option.label" :value="option.value">
              </el-option>
            </el-select>
          </div>
          <el-date-picker size="mini" v-if="searchOptions[item].inputType==='time'"
                          v-model.trim="condition[index][item]"
                          type="datetimerange"
                          :editable="false"
                          class="width380"
                          :placeholder="$t('public.timeRanges')"
                          align="right"
                          >
          </el-date-picker>
          <i v-if="index === 0" class="iconfont icon-zhankai el-icon--right" @click="addOptions"></i>
          <i v-if="index !== 0" class="iconfont icon-zuixiaohua el-icon--right el-icon--red"
            @click="deleteOptions(chooseObject[index.toString()], index)"></i> 
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button @click.stop="handleClose" class="primary_btn">
        {{$t('public.cancel')}}
      </el-button>
      <el-button type="primary" @click.stop="saveSearch" class="primary_btn">
        {{$t('public.save')}}
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
  import {deepClone, getDateTime} from '@/utils/m7Utils'
  export default {
    name: 'Business',
    data () {
      let timeoutData = [{label: this.$t('business.totalTimeStateUncomplete2'), value: true}, {label: this.$t('business.noTimeout'), value: false}]
      let priorityData = [{label: this.$t('business.priority1'), value: '1'}, {label: this.$t('business.priority2'), value: '2', class: 'business-priority2'}, {label: this.$t('business.priority3'), value: '3', class: 'business-priority3'}]
      //工单创建方式数据
      let createModeData = [{label: this.$t('business.sessionCreate'), value: 'webchat'}, {label: this.$t('business.callsCreate'), value: 'call'}, {label: this.$t('business.businessCreation'), value: 'business'}, {label: this.$t('business.interfaceCreate'), value: 'interface'}, {label: this.$t('business.customerCreate'), value:'customer'}, {label: this.$t('business.mailCreate'), value: 'email'}]
      return {
        dialogModel: false,
        agent: [],
        menus: [
          {label: this.$t('business.undealBusiness'), value: 'undeal'},
          {label: this.$t('business.myTodo'), value: 'my'},
          {label: this.$t('business.allBusiness'), value: 'all'}
        ],
        formData: {menu: 'undeal', name: '',type:"and", condition: {createUser:[]}},
        condition: [{createUser:''}],
        stepData:{},
        conditionData:[],
        searchOptions: {
          createUser: {label: this.$t('public.creator'), name: 'createUser', inputType: 'select', data: []},
          query: {label: this.$t('business.customerName'), name: 'query', inputType: 'input'},
          status: {label: this.$t('business.businessStatus'), name: 'status', inputType: 'select', data: [{label: this.$t('business.todo'), value: 'dealing'}, {label: this.$t('business.finished'), value: 'complete'}, {label: this.$t('public.cancel'), value: 'cancel'}]},
          priority: {label: this.$t('business.priorityLabel'), name: 'priority', inputType: 'select', data: priorityData},
          createTime: {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
          processEndTime: {label: this.$t('business.processEndTime'), name: 'processEndTime', inputType: 'time'},
          processTimeout: {label: this.$t('business.overtimeBusiness'), name: 'processTimeout', inputType: 'select', data: timeoutData},
          master: {label: this.$t('business.master'), name: 'master', inputType: 'select', data: []},
          processMember: {label: this.$t('business.partakeAgent'), name: 'processMember', inputType: 'select', data: [], filterable: true},
          createMode:{label: this.$t('business.businessCreationMode'),name: 'createMode', inputType: 'select', data: createModeData},
          flow:{label: this.$t('business.businessFlow'),name: 'flow', inputType: 'select', data: this.$store.state.business.transCache.businessTypes},
          step:{label: this.$t('business.businessStep'),name: 'step', inputType: 'selectAndInput', data: this.$store.state.business.transCache.businessTypes,data1:[]}
        },
        chooseOptions: [
          'createUser'
        ],
        chooseObject: {'0': 'createUser'}
      }
    },
    components: {
    },
    props: {
      type: {type: String, default: 'add'},
      data: {
        type: Object,
        default: function () {
          return {}
        }}
    },
    watch: {
      condition:{
        handler(newVal, oldVal) {
          if(newVal&&newVal.length>0){
            this.conditionData = []
            Object.values(newVal).forEach((item,index)=>{
              this.conditionData.push(Object.keys(item)[0])
            })
            this.conditionData.forEach((item,index)=>{
              this.$set(this.chooseObject, index.toString(), item)
            })
          }else{
            this.conditionData = ['createUser']
          }
        },
        deep: true
      }
    },
    methods: {
      open (item) {
        this.dialogModel = true
        this.$nextTick(() => {
          this.init()
        })
      },
      handleClose () {
        this.dialogModel = false
      },
      saveSearch () {
        if (!this.formData.name) {
          this.$message.error(this.$t('business.customSearchName'))
          return
        } else if (this.formData.name.length > 10) {
          this.$message.error(this.$t('business.customSearchName10'))
          return
        }
        let data = deepClone(this.formData)
        let condition = {}
        this.condition.forEach(item=>{
          Object.keys(item).forEach((i) => {
            if (typeof item[i] === 'string' && !item[i]) {
              delete item[i]
            }else if (typeof item[i] === 'object' && (item[i] &&  item[i].length === 0)||!item[i]) {
              delete item[i]
            }
          })
        })
        //整合成数组，给后端传参
        this.condition.forEach(item=>{
          Object.keys(item).forEach((i) => {
            if(!Object.keys(condition).includes(i)){
              condition[i] = []
            }
            if(i=='stepFlow'){
              condition[i].push(item[i])
            }else{
              if(!condition[i].includes(item[i])){
                condition[i].push(item[i])
              }
            }
          })
        })
        let result = true
        //判断当待领取或者待办菜单时不能选择关单时间以及当前处理人
        if (this.formData.menu === 'undeal' || this.formData.menu === 'my') {
          if (condition.status&&condition.status.length>0) {
            
            condition.status.forEach(item=>{
              if(item !== 'dealing'){
                this.$message.error(this.$t('business.customSearchError1'))
                result = false
              }
            })
          }
          if(condition.processEndTime&&condition.processEndTime.length>0){
            this.$message.error(this.$t('business.customSearchError2'))
            return
          }   
          if (this.formData.menu === 'undeal' && condition.master) {
            this.$message.error(this.$t('business.customSearchError3'))
            return
          }
          if (this.formData.menu === 'my' && condition.master && condition.master.length>0) {
            condition.master.forEach(item=>{
              if(item!== this.$store.state.session.sessionId){
                this.$message.error(this.$t('business.customSearchError4'))
                result = false
              }
            })
          }
        }
        //整理创建时间与关单时间
        if (condition.processEndTime && condition.processEndTime.length>0) {
          let processEndTimeArr = []
          condition.processEndTime.forEach(item=>{
            let obj = {}
            obj.processEndTime$begin = getDateTime(item[0])
            obj.processEndTime$end = getDateTime(item[1])
            processEndTimeArr.push(obj)
            condition.processEndTime = processEndTimeArr
          })
        }
        if (condition.createTime && condition.createTime.length>0) {
          let createTimeArr = []
          condition.createTime.forEach(item=>{
            let obj = {}
            obj.createTime$begin = getDateTime(item[0])
            obj.createTime$end = getDateTime(item[1])
            createTimeArr.push(obj)
            condition.createTime = createTimeArr
          })
        }
        if (Object.keys(condition).length === 0) {
          this.$message.error(this.$t('business.customSearchCondition'))
          return
        }
        //删除工单步骤中工单步骤工单类型相同的值
        if(condition.step&&condition.stepFlow){
          let index = condition.step.length
          condition.stepFlow.splice(index,condition.stepFlow.length-1)
        }
        data.condition = condition
        if(result){
          this.$emit('saveForm', data)
        }
      },
      init () {
        this.chooseObject = {}
        this.chooseOptions = []
        if (this.type === 'add') {
          this.chooseObject = {'0': 'createUser'}
          this.formData = {menu: 'undeal', name: '', type:'and',condition: {createUser: []}}
          this.condition = [{createUser:''}]
        } else if (this.type === 'edit') {
          this.condition = []
          this.formData.menu = this.data.menu || 'undeal'
          this.formData.name = this.data.name || ''
          this.formData.type = this.data.type || 'and'
          let condition = deepClone(this.data.condition) || {}
          Object.keys(condition).forEach((item,index)=>{
            if(condition[item]&&condition[item].length>0){
              //处理时间的回显
              if(item=='createTime'){
                if(condition[item]&&condition[item].length>0){
                  condition[item].forEach((val,index)=>{
                    let timeArr = []
                    timeArr = [new Date(val.createTime$begin), new Date(val.createTime$end)]
                    this.$set(condition[item],index,timeArr)
                  })
                }
              }
              if(item=='processEndTime'){
                if(condition[item]&&condition[item].length>0){
                  condition[item].forEach((val,index)=>{
                    let timeArr = []
                    timeArr = [new Date(val.processEndTime$begin), new Date(val.processEndTime$end)]
                    this.$set(condition[item],index,timeArr)
                  })
                }
              }
              //处理工单步骤工单类型回显
              if(item=='step'){
                condition['stepFlow'].forEach((str,idx)=>{
                  let obj = {}
                  obj[item] = condition[item][idx]
                  obj['stepFlow'] = str
                  this.condition.push(obj)
                })
              }else if(item!=='stepFlow'){
                condition[item].forEach(val=>{
                  let obj = {}
                  obj[item] = val
                  this.condition.push(obj)
                })
              }
            }
          })
          //处理工单步骤列表回显
          this.condition.forEach((item,index)=>{
            if(item.step){
              this.getBusinessFlowStep(this.$store, item.stepFlow,index)
            }
          })
          console.log(this.condition,'condition')
        }
      },
      labelChange (item,index) {
        let str = index.toString()
        let name = this.chooseObject[str]
        this.chooseOptions.splice(index, 1, name)
        this.$delete(this.condition[index],item) 
        this.$set(this.condition[index],name,'')
        if(name=='step'){
          this.$set(this.condition[index],'stepFlow','')
        }else{
          this.$delete(this.condition[index],'stepFlow') 
        }
      },
      addOptions () {
        let select = false
        this.condition.push({})
        for (let i in this.searchOptions) {
          let item = this.searchOptions[i]
          select = true
          if(item.name=='step'){
            this.$set(this.condition[this.condition.length-1],'stepFlow','')
            this.$set(this.condition[this.condition.length-1],'step','')
          }else{
            this.$set(this.condition[this.condition.length-1],item.name,'')
          }
          break
        }
        if (!select) {
          this.$message.error(this.$t('customer.CustomerSearch.noChooseTips'))
        }
      },
      deleteOptions (item, index) {
        this.$delete(this.condition, index.toString())   
        this.condition.forEach((item,index)=>{
          if(item.stepFlow){
            this.getBusinessFlowStep(this.$store, this.condition[index].stepFlow.toString(),index)
          }
        })
      },
      handleChange(selectValue,index){
        this.condition[index].step = ''
        this.getBusinessFlowStep(this.$store, selectValue.toString(),index)
      },
      getBusinessFlowStep(store, flowId,index){
        getBusinessFlowStep(store, flowId).then((flow) => {
          let steps = flow.steps || []
          let stepsSelectData = []
          for (let i = 0; i < steps.length; i++) {
            let stepsItem = steps[i]
            stepsSelectData.push({label: stepsItem.name, value: stepsItem._id})
          }
          this.$set(this.stepData, index.toString(), stepsSelectData)
        })
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
        res.forEach((item) => {
          if (item.status !== 'disable') {
            this.agent.push({label: item.displayName, value: item._id})
          }
        })
        this.searchOptions.createUser.data = this.agent
        this.searchOptions.master.data = this.agent
        this.searchOptions.processMember.data = this.agent
      })
    }
  }
  function getBusinessFlowStep (store, flowId) {
    return store.dispatch('getCache', {type: 'businessFlow', id: flowId})
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl'
  .width190
    width 190px
  .width169
    width 169px
  .width188
    width 188px
  .width380
    width 380px
  .padding
    display inline-block
    padding 0 10px
  .footer
    text-align center
  .el-icon--right
    display inline-block
    margin-left 10px
    color $c-main
    cursor pointer
  .el-icon--red
    color $c-pink
</style>
